package com.hfzy.ihk.web.freeswitchManage.websocket.swx.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.facade.freeswitchManage.enums.SwxInfoTypeEnum;
import com.hfzy.ihk.facade.freeswitchManage.enums.TrunkTypeEnum;
import com.hfzy.ihk.facade.freeswitchManage.service.ReceiveEquipmentService;
import com.hfzy.ihk.facade.websocket.linkcall.enums.SwxEventType;

import com.hfzy.ihk.web.freeswitchManage.websocket.swx.WebSocketManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

/**
 * Created by Administrator on 2016/11/29.
 *
 * @author wws
 */
public class SwxWebSocketHandler implements WebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(SwxWebSocketHandler.class);

    @Autowired
    ReceiveEquipmentService receiveEquipmentService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {


        try {
            logger.info("=====>swx socket 链接成功");
            Map<String, Object> attributes = session.getAttributes();



            String serverId = (String)attributes.get("serverId");

            if (attributes.get("serverId") != null) {
                WebSocketManager.swxServerIdWebSocketSessionMap.put(attributes.get("serverId").toString(), session);
            } else {
                logger.info(">>设备websocket 链接未填serverId websocket");
                //关闭连接
                if (session.isOpen()) {
                    session.close();
                }
            }
        }catch (Exception e){
            logger.error(">>处理 swx websockt 链接逻辑异常",e);
        }

    }


    /**
     * 接收信息方法
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

        try {
            logger.info(">>收到电信设备推送消息并开始处理：{}", message.getPayload().toString());

            JSONObject json = JSONObject.parseObject(message.getPayload().toString());
            if (!json.containsKey("server_id"))
                return;
            if (!json.containsKey("data"))
                return;

            JSONObject data = json.getJSONObject("data");
            if(!data.containsKey("Event")) {
                logger.info(">>收到电信设备推送未进行的处理消息：{}", message.getPayload().toString());
                return;
            }
            if(data.containsKey("Event")){
                String event = data.getString("Event");
                SwxEventType swxEventType = SwxEventType.getEnum(event);

                if(swxEventType==null){
                    logger.info(">>收到电信设备推送未进行的处理消息：{}", message.getPayload().toString());
                    return;
                }
                switch (swxEventType){
                    case SWXLoadupEvent: //开机注册机器成功消息
                        logger.info(">>收到电信设备开机注册成功消息：{}", message.getPayload().toString());
                        receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.MACHINE,message.getPayload().toString());
                        break;
                    case SWXSlotChgEvent: //插换卡消息变更消息

                        logger.info(">>收到电信设备卡槽变跟消息：{}", message.getPayload().toString());
                        receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.CHANGE_SOLT,message.getPayload().toString());
                        break;
                    case SWXActiveSlotEvent:  //卡槽激活消息

                        logger.info(">>收到电信设备卡槽激活消息：{}", message.getPayload().toString());
                        receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.ACTIVE_CARD,message.getPayload().toString());

                        break;
                    case SWXDeviceEntry:   //设备各卡槽详细消息
                        logger.info(">>设备各卡槽详细消息：{}", message.getPayload().toString());
                        receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.SOLT_INFO,message.getPayload().toString());
                        break;
                    case SWXOutOfLimit:   //卡槽超呼叫限制通知
                        logger.info(">>收到卡槽超呼叫限制通知消息：{}", message.getPayload().toString());
                        receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.CALL_LIMIT,message.getPayload().toString());
                        break;
                    case TrunkStatus:   //中继状态通知，只接受通道的中继状态，不接受freeswitch 的中继状态
                        logger.info(">>收到电信设备通道中继状态消息：{}", message.getPayload().toString());
                        if(!data.containsKey("TrunkName"))
                            return;
                        if(data.getString("TrunkName").startsWith("swx")) {
                            receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.CHANNEL_TRUNK_STATUS, message.getPayload().toString());
                        }
                        break;
                    case TrunkEntry:
                        if(!data.containsKey("Trunktype")||!data.containsKey("ActionID"))
                            return;
                        String trunktype = data.getString("Trunktype");
                        String actionID = data.getString("ActionID");
                        if(trunktype.equals("swx")&& TrunkTypeEnum.SWX.getValue().equals(actionID)) {//通道状态,跑job同步更新状态的时候使用
                            receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.CHANNEL_TRUNK, message.getPayload().toString());

                        }else if(trunktype.equals("sip")&&TrunkTypeEnum.SIP.getValue().equals(actionID)){//freeswith 状态，重新启动的时候使用
                            receiveEquipmentService.fsCallReceiveSwxEquipmentInfo(SwxInfoTypeEnum.FREESWITCH_TRUNK, message.getPayload().toString());
                        }
                        logger.info(">>收到主动查询的电信设备通道中继状态消息：{}", message.getPayload().toString());
                        break;
                     default:
                         logger.info(">>收到电信设备推送未进行处理的消息：{}", message.getPayload().toString());
                         break;
                }
            }else{
                logger.info(">>收到电信设备推送未进行处理的消息：{}", message.getPayload().toString());
            }

        }catch (Exception e){
            logger.error(">>处理swx设备推送的消息异常：{}",String.valueOf(message.getPayload()),e);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.info("=====>fs socket 链接错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

        try {
            Map<String, Object> attributes = session.getAttributes();
            if (attributes.get("serverId") == null)
                return;
            String serverId = attributes.get("serverId").toString();
            WebSocketManager.swxServerIdWebSocketSessionMap.remove(serverId);
        }catch (Exception e){
            logger.error(">>swx 关闭websocket 异常",e);
        }

    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
